<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { InventoryReport } from '@/service/api/inventory';
import { useEcharts } from '@/hooks/common/echarts';

const currentMonth = ref($dayjs().valueOf());

// 创建图表
const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  legend: {
    data: [] as string[],
    top: 5,
    right: 20,
    textStyle: {
      fontSize: 11
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '20%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
    axisLine: {
      lineStyle: {
        color: '#E0E6ED'
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#8C8C8C',
      fontSize: 10
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#8C8C8C',
      fontSize: 10
    },
    splitLine: {
      lineStyle: {
        color: '#F0F0F0',
        type: 'dashed'
      }
    }
  },
  series: [] as any[]
}));

// 获取销售图表数据
async function updateChartData() {
  try {
    const date = $dayjs(currentMonth.value);
    const year = date.format('YYYY');
    const month = date.format('MM');

    const response = await InventoryReport.getSellBuyChart({
      year,
      month,
      day: '',
      type: -1
    });

    if (response && !response.error && response.data) {
      // transformBackendResponse已经提取了data，直接使用
      const result = response.data;

      // 处理API数据结构，优先使用series格式
      const categories = result.categories || [];

      if (result.series && result.series.length > 0) {
        // 预定义颜色
        const colors = [
          '#FF9800',
          '#2196F3',
          '#4CAF50',
          '#E91E63',
          '#9C27B0',
          '#607D8B',
          '#009688',
          '#FFC107',
          '#3F51B5',
          '#795548'
        ];

        // 构建图例数据和系列数据
        const legendData = [] as string[];
        const seriesData = [] as any[];

        result.series.forEach((item: any, index: number) => {
          legendData.push(item.name);
          seriesData.push({
            name: item.name,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 4,
            lineStyle: {
              width: 2,
              color: colors[index % colors.length]
            },
            itemStyle: {
              color: colors[index % colors.length]
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: `${colors[index % colors.length]}4D` },
                  { offset: 1, color: `${colors[index % colors.length]}0D` }
                ]
              }
            },
            data: item.data || []
          });
        });

        updateOptions(opts => {
          (opts.xAxis as any).data = categories;
          (opts.legend as any).data = legendData;
          (opts as any).series = seriesData;
          return opts;
        });
      } else if (result.moneyDatas || result.profitDatas) {
        const salesData = result.moneyDatas || [];
        const profitData = result.profitDatas || [];

        updateOptions(opts => {
          (opts.xAxis as any).data = categories;
          (opts.legend as any).data = ['销售金额', '毛利'];
          (opts as any).series = [
            {
              name: '销售金额',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 4,
              lineStyle: {
                width: 2,
                color: '#FF9800'
              },
              itemStyle: {
                color: '#FF9800'
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: 'rgba(255, 152, 0, 0.3)' },
                    { offset: 1, color: 'rgba(255, 152, 0, 0.05)' }
                  ]
                }
              },
              data: salesData
            },
            {
              name: '毛利',
              type: 'line',
              smooth: true,
              symbol: 'circle',
              symbolSize: 4,
              lineStyle: {
                width: 2,
                color: '#4CAF50'
              },
              itemStyle: {
                color: '#4CAF50'
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: 'rgba(76, 175, 80, 0.3)' },
                    { offset: 1, color: 'rgba(76, 175, 80, 0.05)' }
                  ]
                }
              },
              data: profitData
            }
          ];
          return opts;
        });
      } else {
        showEmptyChart();
      }
    } else {
      showEmptyChart();
    }
  } catch (error) {
    // 错误处理 - 在生产环境中可以添加用户友好的提示
    showEmptyChart();
  }
}

// 显示空图表
function showEmptyChart() {
  updateOptions(opts => {
    (opts.xAxis as any).data = [];
    (opts.legend as any).data = [];
    (opts as any).series = [];
    return opts;
  });
}

// 日期变化
function handleDateChange() {
  updateChartData();
}

// 初始化数据 - 使用onMounted替代危险的setTimeout
onMounted(() => {
  updateChartData();
});
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 标题和控制 -->
    <div class="mb-3 flex items-center justify-between px-3">
      <div class="text-sm text-gray-700 font-medium">销售报表</div>
      <div class="flex items-center">
        <NDatePicker
          v-model:value="currentMonth"
          type="month"
          size="small"
          style="width: 100px; font-size: 11px"
          format="YYYY-MM"
          value-format="YYYY-MM-DD"
          @update:value="handleDateChange"
        />
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="flex-1">
      <div ref="domRef" class="h-full min-h-[200px] w-full"></div>
    </div>
  </div>
</template>
